#  Copyright (c) 2021
#  User:SDUFE-Zhaocheng Lu
#  File:history.py
#  Date:2021/08/17 01:07:17

import requests
import base64
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import time


def get_new_captcha():
    global sess
    jpg = sess.get('http://bcfl.sdufe.edu.cn/index.php?g=api&m=checkcode&a=index&time=').content
    file = base64.b64encode(jpg)
    return file


def get_captcha():
    global sess
    file_base64 = get_new_captcha()
    url = 'http://upload.chaojiying.net/Upload/Processing.php'
    data = {
        'user': 'DMSintalor',
        'pass': 'LzC200138',
        'softid': '914617',
        'codetype': '4004',
        'len_min': 0,
        'file_base64': file_base64,
    }
    res = requests.post(url=url, data=data).json()
    return res['pic_str'], res['pic_id']


def post_ERROR(error_id):
    requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data={
        'user': 'DMSintalor',
        'pass': 'LzC200138',
        'softid': '914617',
        'id': error_id,
    })


def qd(info):
    verify_code, verify_id = get_captcha()
    qd_data = {
        'name': info['name'],
        'sex': info['sex'],
        'study_id': info['study_id'],
        'college_id': info['college_id'],
        'address': info['address'],
        'contact': info['contact'],
        'phone': info['phone'],
        'province_id': info['province_id'],
        'city_id': info['city_id'],
        'now_address': info['now_address'],
        'now_status': '1',
        'now_status_msg': '',
        'partition_time': '',
        'behavior': '1',
        'travel_address': '',
        'back_address': '',
        'travel_start': '',
        'travel_back': '',
        'travel_type': '0',
        'travel_number': '',
        'is_public': '0',
        'country_travel': '0',
        'travel_msg': '',
        'other_msg': '',
        'verify': verify_code
    }
    qd_res = sess.post(url='http://bcfl.sdufe.edu.cn/Student/handle_ext_do', data=qd_data).json()
    print(qd_res)
    if qd_res['code'] != 200:
        return False, verify_id
    return True, verify_id


def usr_login(usr):
    print(usr['school_id'])
    verify, pic_id = get_captcha()
    login_res = sess.post(url='http://bcfl.sdufe.edu.cn/Student/handle_login', data={
        'number': usr['school_id'],
        'card': usr['password'],
        'verify': verify
    }).json()
    print(login_res)
    if login_res['code'] != 200:
        return False, pic_id
    else:
        return True, pic_id


def send_result(my_user, content=None):
    my_sender = 'i@py00.top'  # 发件人邮箱账号
    my_pass = 'UhiP8D8i8w6gQsXg'  # 发件人邮箱密码
    server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
    server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
    def mail():
        ret = True
        try:
            if not content:
                msg = MIMEText('恭喜疫情打卡成功，打卡时间：{}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())), 'plain',
                               'utf-8')
            else:
                msg = MIMEText(content, 'plain', 'utf-8')
            msg['From'] = formataddr(["NOTICE！", my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
            msg['To'] = formataddr(["FK", my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
            msg['Subject'] = "疫情打卡结果"  # 邮件的主题，也可以说是标题

            server.sendmail(my_sender, [my_user, ], msg.as_string())
            server.quit()  # 关闭连接
        except Exception:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
            ret = False
        return ret

    ret = mail()
    if ret:
        print("邮件发送成功")
    else:
        print("邮件发送失败")


usr_data_list = [
    {
        'school_id': '20190234306',
        'password': '060067',
        'email': '834036747@qq.com',
        'usr_info': {
            'name': '韩江雪',
            'sex': '0',
            'study_id': '20190234306',
            'college_id': '403',
            'address': '河北省石家庄市平山县圣地汇金港小区',  # 家庭住址
            'contact': '18032792339',  # 个人电话
            'phone': '15233637887',  # 父母（家人）电话
            'province_id': '16',
            'city_id': '170',
            'now_address': '山东财经大学圣井校区',
        }
    },
    {
        'school_id': '20190514238',
        'password': '131547',
        'email': '1840492573@qq.com',
        'usr_info': {
            'name': '刘婉婷',
            'sex': '0',
            'study_id': '20190514238',
            'college_id': '406',
            'address': '宁夏回族自治区吴忠市利通区清河苑',  # 家庭住址
            'contact': '18009536144',  # 个人电话
            'phone': '13895248366',  # 父母（家人）电话
            'province_id': '31',
            'city_id': '358',
            'now_address': '宁夏回族自治区吴忠市利通区清河苑',
        }
    },
    {
        'school_id': '20191864133',
        'password': '046115',
        'email': '2538262357@qq.com',
        'usr_info': {
            'name': '马汝钊',
            'sex': '1',
            'study_id': '20191864133',
            'college_id': '419',
            'address': '山东省济南市章丘区山水泉城3号楼1单元',  # 家庭住址
            'contact': '15339967570',  # 个人电话
            'phone': '13954177424',  # 父母（家人）电话
            'province_id': '16',
            'city_id': '170',
            'now_address': '山东省济南市章丘区山水泉城3号楼1单元',
        }
    }
]
if __name__ == '__main__':
    success_list = []
    error_list = []
    for usr_data in usr_data_list:
        sess = requests.session()
        sess.get('http://bcfl.sdufe.edu.cn/index/login')
        login_status, login_pic_id = usr_login(usr_data)
        login_cnt = 0
        while not login_status and login_cnt < 3:
            post_ERROR(error_id=login_pic_id)
            login_status, login_pic_id = usr_login(usr_data)
            login_cnt += 1
        if login_cnt >= 3:
            error_list.append(usr_data['school_id'])
            send_result(usr_data['email'], '请注意，疫情打卡失败！')
            continue
        sess.get('http://bcfl.sdufe.edu.cn/student/handle_ext.html')
        qd_status, qd_pic_id = qd(usr_data['usr_info'])
        qd_cnt = 0
        while not qd_status and qd_cnt < 3:
            qd_cnt += 1
            post_ERROR(error_id=qd_pic_id)
            qd_status, qd_pic_id = qd(usr_data['usr_info'])
        if qd_cnt >= 3:
            error_list.append(usr_data['school_id'])
            send_result(usr_data['email'], '请注意，疫情打卡失败！')
            continue
        success_list.append(usr_data['school_id'])
        send_result(usr_data['email'])
        time.sleep(3)
    send_result('1256234567@qq.com', '打卡成功：{}\n打卡失败：{}'.format(success_list, error_list))
